package com.hy;

import java.util.HashMap;
import java.util.Map;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:HTML 实体解析器
 * author: Mr.Du
 * Date: 2023/11/23
 * Time: 10:02
 */
public class EntityParser {

    public String entityParser(String text) {
        Map<String,String> mp = new HashMap<>();
        mp.put("&quot;","\\\"");
        mp.put("&apos;","'");
        mp.put("&amp;","&");
        mp.put("&gt;",">");
        mp.put("&lt;","<");
        mp.put("&frasl;","/");
        StringBuilder sb = new StringBuilder();
        String[] strs = text.split(" ");
        for(int i = 0;i < strs.length;i++){
            sb.append(change(strs[i], mp) + " ");
        }
        return sb.toString().trim();
    }

    public String change(String s,  Map<String,String> mp){
        StringBuilder sb = new StringBuilder();
        while(s.indexOf("&") != -1){
            int i = s.indexOf("&");
            sb.append(s.substring(0, i));
            String s1 = s.substring(i);
            int j = s1.indexOf(";");
            if(j == -1 || j - i > 6){
                break;
            }
            String str = s.substring(i, i + j + 1);
            String add = mp.getOrDefault(str, str);
            if(add.equals(str)){
                sb.append(s.charAt(i));
                s = s.substring(i + 1);
            }else{
                sb.append(add);
                s = s.substring(i + j + 1);
            }
        }
        sb.append(s);
        return sb.toString();
    }

    public static void main(String[] args) {
        EntityParser entityParser = new EntityParser();

        String res = entityParser.entityParser("&&gt;");
        res = entityParser.entityParser(" &amp; &gt; 8|eK8FDRO");
        System.out.println(res);
    }
}
